import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000
})

// request interceptor
service.interceptors.request.use((config) => {
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
},
error => {
  console.log(error) // for debug
  return Promise.reject(error)
})

service.interceptors.response.use((response) => {
  if (response.data.code === 50000) {
    Message({
      message: response.data.msg,
      type: 'error'
    })
  }
  return response.data
},
error => {
  if (error.response.status === 401) {
    Message({
      message: '登录过期了',
      type: 'error'
    })
    store.dispatch('user/logout')
    router.replace('/login')
  } else {
    Message({
      message: error.response.data.msg,
      type: 'error'
    })
  }
  return Promise.reject(error)
}
)

export default service
